/**
 * @description 数据分析工具
 * @author 张一依有把越女剑
 * @date 2025-04-16
 */

// 分析考试数据
export function analyzeExamData(examRecords) {
	if (!examRecords || examRecords.length === 0) {
		return {
			totalParticipants: 0,
			averageScore: 0,
			passRate: 0,
			departmentStats: {},
			scoreDistribution: {},
			timeAnalysis: {}
		}
	}
	
	// 基础统计
	const totalParticipants = examRecords.length
	const totalScore = examRecords.reduce((sum, record) => sum + record.score, 0)
	const averageScore = Math.round(totalScore / totalParticipants)
	const passCount = examRecords.filter(record => record.score >= 60).length
	const passRate = Math.round((passCount / totalParticipants) * 100)
	
	// 部门统计
	const departmentStats = {}
	examRecords.forEach(record => {
		const dept = record.department || '未知部门'
		if (!departmentStats[dept]) {
			departmentStats[dept] = {
				count: 0,
				totalScore: 0,
				passCount: 0,
				averageScore: 0,
				passRate: 0
			}
		}
		departmentStats[dept].count++
		departmentStats[dept].totalScore += record.score
		if (record.score >= 60) {
			departmentStats[dept].passCount++
		}
	})
	
	// 计算部门平均分和通过率
	Object.keys(departmentStats).forEach(dept => {
		const stats = departmentStats[dept]
		stats.averageScore = Math.round(stats.totalScore / stats.count)
		stats.passRate = Math.round((stats.passCount / stats.count) * 100)
	})
	
	// 分数分布
	const scoreDistribution = {
		'90-100': 0,
		'80-89': 0,
		'70-79': 0,
		'60-69': 0,
		'0-59': 0
	}
	
	examRecords.forEach(record => {
		const score = record.score
		if (score >= 90) scoreDistribution['90-100']++
		else if (score >= 80) scoreDistribution['80-89']++
		else if (score >= 70) scoreDistribution['70-79']++
		else if (score >= 60) scoreDistribution['60-69']++
		else scoreDistribution['0-59']++
	})
	
	// 时间分析
	const timeAnalysis = analyzeTimeData(examRecords)
	
	return {
		totalParticipants,
		averageScore,
		passRate,
		departmentStats,
		scoreDistribution,
		timeAnalysis
	}
}

// 分析时间数据
function analyzeTimeData(examRecords) {
	const now = Date.now()
	const oneDay = 24 * 60 * 60 * 1000
	const oneWeek = 7 * oneDay
	const oneMonth = 30 * oneDay
	
	const timeStats = {
		today: 0,
		thisWeek: 0,
		thisMonth: 0,
		dailyStats: {}
	}
	
	examRecords.forEach(record => {
		const timeDiff = now - record.submitTime
		
		if (timeDiff <= oneDay) timeStats.today++
		if (timeDiff <= oneWeek) timeStats.thisWeek++
		if (timeDiff <= oneMonth) timeStats.thisMonth++
		
		// 按日期统计
		const date = new Date(record.submitTime).toDateString()
		if (!timeStats.dailyStats[date]) {
			timeStats.dailyStats[date] = 0
		}
		timeStats.dailyStats[date]++
	})
	
	return timeStats
}

// 生成考试报告
export function generateExamReport(examRecords) {
	const analysis = analyzeExamData(examRecords)
	
	let report = '# 安全生产考试数据分析报告\n\n'
	report += `## 总体概况\n`
	report += `- 参与人数：${analysis.totalParticipants}人\n`
	report += `- 平均分：${analysis.averageScore}分\n`
	report += `- 通过率：${analysis.passRate}%\n\n`
	
	report += `## 分数分布\n`
	Object.entries(analysis.scoreDistribution).forEach(([range, count]) => {
		const percentage = analysis.totalParticipants > 0 ? 
			Math.round((count / analysis.totalParticipants) * 100) : 0
		report += `- ${range}分：${count}人 (${percentage}%)\n`
	})
	report += '\n'
	
	report += `## 部门统计\n`
	Object.entries(analysis.departmentStats).forEach(([dept, stats]) => {
		report += `### ${dept}\n`
		report += `- 参与人数：${stats.count}人\n`
		report += `- 平均分：${stats.averageScore}分\n`
		report += `- 通过率：${stats.passRate}%\n\n`
	})
	
	report += `## 时间分析\n`
	report += `- 今日考试：${analysis.timeAnalysis.today}人\n`
	report += `- 本周考试：${analysis.timeAnalysis.thisWeek}人\n`
	report += `- 本月考试：${analysis.timeAnalysis.thisMonth}人\n\n`
	
	return report
}

// 导出数据为CSV格式
export function exportToCSV(examRecords) {
	if (!examRecords || examRecords.length === 0) {
		return ''
	}
	
	let csv = '姓名,部门,分数,考试时间,是否通过\n'
	
	examRecords.forEach(record => {
		const date = new Date(record.submitTime).toLocaleString('zh-CN')
		const passed = record.score >= 60 ? '是' : '否'
		csv += `"${record.name}","${record.department}",${record.score},"${date}","${passed}"\n`
	})
	
	return csv
}

// 导出数据为Excel格式（HTML表格）
export function exportToExcel(examRecords) {
	if (!examRecords || examRecords.length === 0) {
		return ''
	}
	
	let html = '<table border="1" style="border-collapse: collapse;">\n'
	html += '<tr style="background-color: #f0f0f0; font-weight: bold;">\n'
	html += '<th>姓名</th><th>部门</th><th>分数</th><th>考试时间</th><th>是否通过</th>\n'
	html += '</tr>\n'
	
	examRecords.forEach(record => {
		const date = new Date(record.submitTime).toLocaleString('zh-CN')
		const passed = record.score >= 60 ? '是' : '否'
		const rowColor = record.score >= 60 ? '#e6f7ff' : '#fff2e8'
		
		html += `<tr style="background-color: ${rowColor};">\n`
		html += `<td>${record.name}</td>`
		html += `<td>${record.department}</td>`
		html += `<td>${record.score}</td>`
		html += `<td>${date}</td>`
		html += `<td>${passed}</td>\n`
		html += '</tr>\n'
	})
	
	html += '</table>'
	return html
}

// 获取排行榜数据
export function getRankingData(examRecords, limit = 10) {
	if (!examRecords || examRecords.length === 0) {
		return []
	}
	
	// 去重并按分数排序
	const uniqueRecords = getUniqueRecords(examRecords)
	const sortedRecords = uniqueRecords.sort((a, b) => {
		if (b.score !== a.score) {
			return b.score - a.score // 按分数降序
		}
		return a.submitTime - b.submitTime // 分数相同按时间升序
	})
	
	return sortedRecords.slice(0, limit).map((record, index) => ({
		...record,
		rank: index + 1
	}))
}

// 去除重复记录（同名同部门只保留最新的）
function getUniqueRecords(examRecords) {
	const recordMap = new Map()
	
	examRecords.forEach(record => {
		const key = `${record.name}-${record.department}`
		if (!recordMap.has(key) || record.submitTime > recordMap.get(key).submitTime) {
			recordMap.set(key, record)
		}
	})
	
	return Array.from(recordMap.values())
}
